# -*- coding: utf-8 -*-
import os
import time
import uuid
from app.model.filedata import Filedata
from werkzeug.utils import secure_filename
from app import app, slash, SITE_URL, db, ALLOW_EXTENSIONS, SAVE_UPLOAD_FOLDER
from flask import request, redirect, url_for, jsonify
from app.util.file import compress_image, getMd5


@app.route("/show/<filename>/")  # 换成static后此接口可以不用了
def show_files(filename):
    print(request.path)
    return redirect(url_for('static', filename='file/image/upload/' + filename))


@app.route("/", methods=['GET', 'POST'])
def upload_files():
    if request.method == "POST":
        file = request.files["file"]
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            uid = str(uuid.uuid4())
            file_name = uid + "." + filename.rsplit(".", 1)[1]
            file_name = file_name.replace("-", "")  # 保存名字
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], file_name))
            base_path = os.getcwd()
            file_path = base_path + slash + app.config["UPLOAD_FOLDER"] + slash + file_name  # 保存地址

            file_hash = getMd5(app.config["UPLOAD_FOLDER"] + slash + file_name)
            hasHash = Filedata.query.filter_by(filehash=file_hash).first()
            if hasHash != None:
                return jsonify({"errno": "1", "errmsg": u"此文件已存在"})

            thumbName = (SAVE_UPLOAD_FOLDER + slash + uid + "_thumb." + filename.rsplit(".", 1)[1]).replace("-", "")
            print(thumbName)
            thumb = compress_image(app.config["UPLOAD_FOLDER"] + slash + file_name, "app/" + thumbName, 50)
            filesize = os.path.getsize(app.config["UPLOAD_FOLDER"] + slash + file_name)
            filedata = Filedata(
                userid=100,
                filename=file.filename,
                fileurl=SITE_URL + SAVE_UPLOAD_FOLDER + slash + file_name,
                filehash=file_hash,
                filethumb=SITE_URL + thumbName,
                size=filesize / 1024,
                source=1,
                created_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                updated_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
            db.session.add(filedata)
            db.session.commit()

            print(file_path)
            return jsonify({"errno": "0", "errmsg": u"success"})

    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
    <p><input type=file name=file>
    <input type=submit value=Upload>
    </form>
    '''


def allowed_file(filename):
    return "." in filename and \
           filename.rsplit(".", 1)[1] in ALLOW_EXTENSIONS
